import { Request, Response } from 'express';
import ApiResponse from '@/utils/api/api-response.util';
import noticeService from '@/services/system/notice.service';
import { AuthRequest } from '@/types';
import { getLogger } from '@/utils/logger';
import { Log, BusinessType } from '@/decorators/Log';
import { RepeatSubmit } from '@/decorators/repeatSubmit.decorator';

// 创建模块专用的日志记录器
const consoleLogger = getLogger("notice-controller");
const logger = getLogger("notice-controller", {
	console: false,
});

/**
 * 通知公告控制器
 */
class NoticeController {
  /**
   * 公告分页列表
   * @param req 请求对象
   * @param res 响应对象
   */
  async list(req: Request, res: Response) {
    try {
      // 请求日志
      consoleLogger.info("获取公告分页列表请求", {
        query: req.query,
        operator: req.user?.userName || 'unknown',
      });
      
      const { page, pageSize, noticeTitle, noticeType, status } = req.query;
      const result = await noticeService.list({
        page: Number(page) || 1,
        pageSize: Number(pageSize) || 10,
        noticeTitle,
        noticeType,
        status
      });
      
      // 结果日志
      logger.info("获取公告分页列表成功", {
        response: {
          page: Number(page) || 1,
          pageSize: Number(pageSize) || 10,
          total: result?.total || 0,
          count: result?.rows?.length || 0,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.successWithoutWrapper(res, result);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取公告分页列表失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          query: req.query,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '获取公告分页列表失败', 500);
      }
    }
  }

  /**
   * 公告详情
   * @param req 请求对象
   * @param res 响应对象
   */
  async detail(req: Request, res: Response) {
    try {
      const { noticeId } = req.params;
      const id = Number(noticeId);
      
      // 请求日志
      consoleLogger.info("获取公告详情请求", {
        params: req.params,
        noticeId: id,
        operator: req.user?.userName || 'unknown',
      });
      
      const data = await noticeService.detail(id);
      
      if (!data) {
        consoleLogger.warn('获取公告详情 - 公告不存在', { id });
        ApiResponse.error(res, '公告不存在', 404);
        return;
      }
      
      // 结果日志
      logger.info("获取公告详情成功", {
        response: {
          noticeId: id,
          data,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, data);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取公告详情失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '获取公告详情失败', 500);
      }
    }
  }
  
  /**
   * 新增通知公告
   * @param req 请求对象
   * @param res 响应对象
   */
  @RepeatSubmit({ expireSeconds: 5 })
  @Log({ title: '通知公告', businessType: BusinessType.INSERT })
  async add(req: AuthRequest, res: Response) {
    try {
      // 请求日志
      consoleLogger.info("新增通知公告请求", {
        body: req.body,
        operator: req.user?.userName || 'unknown',
      });
      
      const data = req.body;
      data.createBy = req.user?.userName || '';
      
      const result = await noticeService.add(data);
      
      // 结果日志
      logger.info("新增通知公告成功", {
        response: {
          noticeTitle: data.noticeTitle,
          noticeType: data.noticeType,
          result,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, result, '新增成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`新增通知公告失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          body: req.body,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '新增通知公告失败', 500);
      }
    }
  }
  
  /**
   * 修改通知公告
   * @param req 请求对象
   * @param res 响应对象
   */
  @RepeatSubmit({ expireSeconds: 5 })
  @Log({ title: '通知公告', businessType: BusinessType.UPDATE })
  async update(req: AuthRequest, res: Response) {
    try {
      // 请求日志
      consoleLogger.info("修改通知公告请求", {
        body: req.body,
        operator: req.user?.userName || 'unknown',
      });
      
      const { noticeId } = req.body;
      const id = Number(noticeId);
      
      const data = req.body;
      data.updateBy = req.user?.userName || '';
      
      const result = await noticeService.update(id, data);
      
      // 结果日志
      logger.info("修改通知公告成功", {
        response: {
          noticeId: id,
          noticeTitle: data.noticeTitle,
          noticeType: data.noticeType,
          result,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, result, '修改成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`修改通知公告失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          body: req.body,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '修改通知公告失败', 500);
      }
    }
  }
  
  /**
   * 删除通知公告
   * @param req 请求对象
   * @param res 响应对象
   */
  @RepeatSubmit({ expireSeconds: 5 })
  @Log({ title: '通知公告', businessType: BusinessType.DELETE })
  async remove(req: AuthRequest, res: Response) {
    try {
      const noticeIds = req.params.noticeIds.split(",").map((noticeId: string) => parseInt(noticeId));
      const operator = req.user?.userName || 'admin';
      
      // 请求日志
      consoleLogger.info("删除通知公告请求", {
        params: req.params,
        noticeIds,
        operator,
      });
      
      const result = await noticeService.deleteNoticeByIds(noticeIds);
      
      // 结果日志
      logger.info("删除通知公告成功", {
        response: {
          noticeIds,
          result,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, result, '删除成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`删除通知公告失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, '删除通知公告失败', 500);
      }
    }
  }
}

export default new NoticeController(); 